package com.jieli.bt.att.ui.device

import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothProfile
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.jieli.bt.att.R
import com.jieli.bt.att.data.device.DeviceConnection
import com.jieli.bt.att.util.BluetoothUtil
import com.jieli.bt.att.util.ViewUtil
import com.jieli.bt.att.util.hide
import com.jieli.bt.att.util.show

/**
 * ConnectedDeviceAdapter
 * @author zqjasonZhong
 * @since 2025/3/28
 * @email zhongzhuocheng@zh-jieli.com
 * @desc 已连接设备的适配器
 */
class ConnectedDeviceAdapter:BaseQuickAdapter<DeviceConnection, BaseViewHolder>(R.layout.item_connected_device) {

    init {
        addChildClickViewIds(R.id.iv_info)
    }

    override fun convert(holder: BaseViewHolder, item: DeviceConnection) {
        holder.setText(R.id.tv_device_name, BluetoothUtil.getDeviceName(item.device, false))
        holder.setText(R.id.tv_device_address, item.device.address)
        holder.setText(R.id.tv_connection, ViewUtil.connectionString(context, item.state))
        holder.getView<View>(R.id.view_line).apply {
            if (isLastItem(item)) hide() else show()
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    fun updateItem(connection: DeviceConnection) {
        val item = findItem(connection.device) ?: return
        item.state = connection.state
        if (item.state != BluetoothProfile.STATE_CONNECTED) {
            data.remove(item)
            notifyDataSetChanged()
        } else {
            notifyItemChanged(getItemPosition(item))
        }
    }

    private fun isLastItem(item: DeviceConnection): Boolean {
        return getItemPosition(item) == data.size - 1
    }

    private fun findItem(device: BluetoothDevice): DeviceConnection? {
        if (data.isEmpty()) return null
        for (scanDevice in data) {
            if (BluetoothUtil.deviceEquals(device, scanDevice.device)) {
                return scanDevice
            }
        }
        return null
    }
}